package com.emode.util;

import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.json.JSONObject;

/**
 * 小小工具
 * @author qdmmy6
 *
 */
public class CommonUtils {
	private static Logger logger = Logger.getLogger(CommonUtils.class);
	/**
	 * 返回一个不重复的字符串
	 * @return
	 */
	public static String uuid() {
		return UUID.randomUUID().toString().replace("-", "").toUpperCase();
	}

	/**
	 * 把map转换成对象
	 * @param map
	 * @param clazz
	 * @return
	 * 
	 * 把Map转换成指定类型
	 */
	@SuppressWarnings("rawtypes")
	public static <T> T toBean(Map map, Class<T> clazz) {
		try {
			/*
			 * 1. 通过参数clazz创建实例
			 * 2. 使用BeanUtils.populate把map的数据封闭到bean中
			 */
			T bean = clazz.newInstance();
			ConvertUtils.register(new DateConverter(), java.util.Date.class);
			BeanUtils.populate(bean, map);
			return bean;
		} catch(Exception e) {
			throw new RuntimeException(e);
		}
	}
	/**
	 * 用于将json串返回前台解析
	 * @param response
	 * @param jsonStr
	 */
	public static void returnJson(String jsonStr)
	{
	HttpServletResponse response = 	ServletActionContext.getResponse();
	response.setContentType(
				"text/javascript;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("appliction/json");
		try {
			PrintWriter out = response.getWriter();
			//out = response.getWriter();
			out.write(jsonStr);
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.error(e);
		}
	}
	public static void returnMapToJson(Map map)
	{
		HttpServletResponse response = 	ServletActionContext.getResponse();
		response.setContentType(
				"text/javascript;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("appliction/json");
		try {
			JSONObject obj = new JSONObject(map);
			PrintWriter out =response.getWriter();
			//out = response.getWriter();
			out.write(obj.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.error(e);
		}
	}
	public static void resultMapToJson(Map<String,Object> map)
	{
		HttpServletResponse response = 	ServletActionContext.getResponse();
		response.setContentType(
				"text/javascript;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("appliction/json");
		try {
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("result", map);
			JSONObject obj = new JSONObject(result);
			PrintWriter out =response.getWriter();
			//out = response.getWriter();
			out.write(obj.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.error(e);
		}
	}
	
	public static Map<String, String> getValueMap(Object obj) {  
		  
        Map<String, String> map = new HashMap<String, String>();  
        // System.out.println(obj.getClass());  
        // 获取f对象对应类中的所有属性域  
        Field[] fields = obj.getClass().getDeclaredFields();  
        for (int i = 0, len = fields.length; i < len; i++) {  
            String varName = fields[i].getName();  
            try {  
                // 获取原来的访问控制权限  
                boolean accessFlag = fields[i].isAccessible();  
                // 修改访问控制权限  
                fields[i].setAccessible(true);  
                // 获取在对象f中属性fields[i]对应的对象中的变量  
                Object o = fields[i].get(obj);  
                if (o != null)  
                    map.put(varName, o.toString());  
                // System.out.println("传入的对象中包含一个如下的变量：" + varName + " = " + o);  
                // 恢复访问控制权限  
                fields[i].setAccessible(accessFlag);  
            } catch (IllegalArgumentException ex) {  
                ex.printStackTrace();  
            } catch (IllegalAccessException ex) {  
                ex.printStackTrace();  
            }  
        }  
        return map;  
  
    }  
	
	
}
